package com.jiahua.user.biz.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.jiahua.user.biz.dao.CustomerDao;
import com.jiahua.user.biz.model.Customer;

public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {

	final Logger logger = Logger.getLogger(CustomerDaoImpl.class.getName());

	@Override
	public boolean saveCustomer(Customer customer) {
		boolean result = true;
		try {
			getHibernateTemplate().save(customer);
		} catch (DataAccessException e) {
			result = false;
			e.printStackTrace();
		} catch (Exception e) {
			result = false;
			e.printStackTrace();
		}
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> getListCustomer(int topNum) {
		HibernateTemplate ht = getHibernateTemplate();
		ht.setMaxResults(topNum);
		return ht.find("from Customer");
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Customer> getListAllCustomer() {
		return getHibernateTemplate().find("from Customer");
	}

	@Override
	public Customer verifyLoginInfo(String loginId, String password) {
		Session session = getSession(true);
		List list = new ArrayList();
		Criteria criteria = session.createCriteria(Customer.class);
		criteria.add(Restrictions.or(Restrictions.eq("loginid", loginId), Restrictions.eq("email", loginId)));
		criteria.add(Restrictions.eq("password", password));
		list = criteria.list();

		if (list.size() > 0) {
			return (Customer) list.get(0);
		}
		return null;
	}

	@Override
	public boolean deleteCustomer(String id) {

		boolean result = false;
		Customer customer = new Customer();
		customer.setCustomerID(id);
		try {
			getHibernateTemplate().delete(customer);
			result = true;
		} catch (DataAccessException e) {
			result = false;
			e.printStackTrace();
		}

		return result;
	}


}
